<!-- eslint-disable vue/no-parsing-error -->
<template>
  <div class="work-manage">
    <!-- 作业信息部分 -->
    <div class="work-info">
      <div class="header">
        <h3>{{ workInfo.title }}</h3>
        <div class="tags">
          <el-tag>{{ workInfo.type === 1 ? '个人作业' : '小组作业' }}</el-tag>
          <el-tag>截止时间: {{ formatDate(workInfo.endTime) }}</el-tag>
          <el-tag>{{ workInfo.score }}分</el-tag>
        </div>
        <div class="content">{{ workInfo.content }}</div>
      </div>
      <div class="top_r">
        <el-switch v-model="scoreVisible" @change="isShowScore(scoreVisible)">
        </el-switch>
        <span v-if="scoreVisible">对学生显示成绩</span>
        <span v-else>对学生隐藏成绩</span>
      </div>
    </div>

    <!-- 学生作业列表部分 -->
<div class="filter-section">
    <el-input
      v-model="searchName"
      placeholder="请输入学生姓名"
      style="width: 200px; margin-right: 20px;"
      @input="handleSearch"
    />
    
    <el-radio-group v-model="filterStatus" @change="handleFilterChange">
      // eslint-disable-next-line vue/no-parsing-error
      <el-radio-button :label="null">全部({{ total }})</el-radio-button>
      <el-radio-button :label="0">未交({{ unsubmittedCount }})</el-radio-button>
      <el-radio-button :label="1">提交未批改({{ submittedCount }})</el-radio-button>
      <el-radio-button :label="2">提交已批改({{ gradedCount }})</el-radio-button>
    </el-radio-group>
  </div>

  <!-- 修改表格部分 -->
  <el-table :data="studentWorks" @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" />
    <el-table-column prop="username" label="姓名" />
    <el-table-column prop="studentId" label="学号" />
    <el-table-column prop="tag" label="所属标签" >
    <template #default>
      <span>默认标签</span>
    </template>
   </el-table-column>
    <el-table-column prop="submitTime" label="提交时间" :formatter="formatDate" >
    <template #default="scope">
      <span>{{ scope.row.submitTime ? formatDate(scope.row.submitTime) : '' }}</span>
    </template>
  </el-table-column>
  <el-table-column prop="score" label="成绩">
  <template #default="scope">
    <span 
      v-if="scope.row.status === 0" 
      style="color: #f56c6c; cursor: pointer;"
      @click="handleUnsubmittedClick(scope.row)"
    >
      未交
    </span>
    <span v-else>{{ scope.row.score }}</span>
  </template>
</el-table-column>
    <el-table-column label="操作" width="200">
      <template #default="scope">
        <!-- 未提交状态显示催交按钮 -->
        <el-button 
          v-if="scope.row.status === 0"
          type="primary"
          size="small"
          @click="handleExpedite(scope.row.id)"
        >
          催交
        </el-button>

        <!-- 已提交状态显示查看和评分按钮 -->
        <template v-else>
          <el-button 
            type="primary"
            size="small"
            @click="viewWork(scope.row)"
          >
            查看
          </el-button>
          <el-button 
            type="primary"
            size="small"
            @click="gradeWork(scope.row)"
          >
            评分
          </el-button>
        </template>
      </template>
    </el-table-column>
  </el-table>

   <el-pagination
    v-model:current-page="currentPage"
    v-model:page-size="pageSize"
    :total="total"
    :page-sizes="[10, 20, 50, 100]"
    layout="total, sizes, prev, pager, next"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
   />

    <!-- 查看作业预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="查看作业"
      width="800px"
    >
      <div v-if="previewWork">
        <div class="work-preview-info">
          <p>学生：{{ previewWork.username }}</p>
          <p>提交时间：{{ formatDate(previewWork.submitTime) }}</p>
          <p>状态：{{ getStatusText(previewWork.status) }}</p>
        </div>
        
        <!-- 作业内容预览 -->
        <div class="work-preview-content">
          <!-- 如果有图片则显示图片 -->
          <div v-if="previewWork.files && previewWork.files.length > 0">
            <el-image
              v-for="file in previewWork.files"
              :key="file.id"
              :src="file.url"
              :preview-src-list="previewWork.files.map(f => f.url)"
              fit="contain"
              class="preview-image"
            />
          </div>
          <!-- 如果没有文件 -->
          <div v-else class="no-content">
            暂无提交内容
          </div>
        </div>
      </div>
    
      <template #footer>
        <el-button @click="previewDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    
    <!-- 打分对话框 -->
    <el-dialog
      v-model="gradeDialogVisible"
      title="学生作业"
      width="600px"
    >
      <el-form :model="gradeForm" label-width="100px">
        <el-form-item label="学生姓名">
          <el-input v-model="gradeForm.username" disabled />
        </el-form-item>
        
        <el-form-item label="学号">
          <el-input v-model="gradeForm.studentId" disabled />
        </el-form-item>
    
        <el-form-item label="所属标签">
          <el-input v-model="gradeForm.tag" disabled />
        </el-form-item>
    
        <el-form-item label="提交时间">
          <el-input v-model="gradeForm.submitTime" disabled />
        </el-form-item>
    
        <el-form-item label="作业内容">
          <el-input
            type="textarea"
            v-model="gradeForm.content"
            rows="4"
            disabled
          />
        </el-form-item>
    
        <el-form-item label="下载作业">
          <el-button 
            type="primary" 
            link
            @click="downloadWork(gradeForm.fileUrl)"
          >
            下载作业
          </el-button>
        </el-form-item>
    
        <el-form-item label="成绩">
          <el-input v-model="gradeForm.score" />
        </el-form-item>
      </el-form>
    
      <template #footer>
        <el-button @click="gradeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitGrade">确定</el-button>
      </template>
    </el-dialog>
</div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getWorkInfo, getStudentWorks, submitWorkGrade ,expediteSubmission,updateWorkStatus} from '@/api/work.js'

const workId = 4

// 响应式数据
const workInfo = ref({})
const studentWorks = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const filterStatus = ref()
const selectedWorks = ref([])
const scoreVisible = ref(false)
const gradeDialogVisible = ref(false)
const previewDialogVisible = ref(false)
const previewWork = ref(null)
const searchName = ref('')
const gradedCount = ref(0)

const gradeForm = ref({
  studentWorkId: null,
  score: 0,
  message: ''
})

// 统计数据
const unsubmittedCount = ref(0)
const submittedCount = ref(0)

// 获取作业信息
const fetchWorkInfo = async () => {
  try {
    console.log('开始获取作业信息，workId:', workId, 'type:', typeof workId)
    if (!workId) {
      throw new Error('作业ID不能为空')
    }
    const res = await getWorkInfo(workId)
    console.log('作业信息接口返回：', res)
    workInfo.value = res.data
    console.log('作业信息：', workInfo.value)
  } catch (error) {
    console.error('获取作业信息失败：', error)
    ElMessage.error(error.message || '获取作业信息失败')
  }
}


// 获取学生作业列表
const fetchStudentWorks = async () => {
  try {
    const params = {
      workId,
      page: currentPage.value,
      pageSize: pageSize.value,
      status: filterStatus.value || null,
      studentName: searchName.value
    }
    const res = await getStudentWorks(params)
    
    if (res.data && Array.isArray(res.data.list)) {
      studentWorks.value = res.data.list
      total.value = res.data.total
      unsubmittedCount.value = res.data.unsubmittedCount
      submittedCount.value = res.data.submittedCount
      gradedCount.value = res.data.gradedCount
    } else {
      console.error('接口返回数据结构异常：', res)
      ElMessage.error('数据格式异常')
    }
  } catch (error) {
    console.error('获取学生作业列表失败：', error)
    ElMessage.error('获取学生作业列表失败')
  }
}

// 添加搜索处理方法
const handleSearch = () => {
  currentPage.value = 1
  fetchStudentWorks()
}

// 添加未交点击处理方法
const handleUnsubmittedClick = (row) => {
  ElMessageBox.confirm(
    '确定将该学生作业状态改为已交吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {

      await updateWorkStatus(row.id, 1)
            // 更新本地数据状态
            row.status = 1
      
      
      ElMessage({
        type: 'success',
        message: '状态已更新为已交'
      })
      
      // 重新获取列表数据以更新计数等信息
      fetchStudentWorks()
    } catch (error) {
      ElMessage.error('更新状态失败')
    }
  }).catch(() => {
    // 用户点击取消，不做任何操作
  })
}

// 查看作业（预览）
const viewWork = (row) => {
  if (!row.files || row.files.length === 0) {
    ElMessage.warning('暂无提交内容')
    return
  }
  previewWork.value = row
  previewDialogVisible.value = true
}

// 评分
const gradeWork = (row) => {
  gradeForm.value = {
    studentWorkId: row.id,
    score: row.score || 0,
    message: row.message || '',
    studentName: row.studentName,
    studentId: row.studentId,
    submitTime: row.submitTime,
    files: row.files || []
  }
  gradeDialogVisible.value = true
}
const isShowScore = (value) => {
  if (value) {
    ElMessage.success('已对学生显示成绩')
  } else {
    ElMessage.warning('已对学生隐藏成绩')
  }
}

const submitGrade = async () => {
  try {
    await submitWorkGrade(gradeForm.value)
    ElMessage.success('评分成功')
    gradeDialogVisible.value = false
    fetchStudentWorks()
  } catch (error) {
    ElMessage.error('评分失败')
  }
}

// 批量操作相关方法
const handleSelectionChange = (selection) => {
  selectedWorks.value = selection
}

const handleFilterChange = (value) => {
  filterStatus.value = value
  fetchStudentWorks()
}


// 添加催交处理方法
const handleExpedite = async (id) => {
  try {
    await expediteSubmission(id)
    ElMessage.success('已发送催交提醒')
    fetchStudentWorks()
  } catch (error) {
    ElMessage.error('催交失败')
  }
}

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchStudentWorks()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchStudentWorks()
}

// 工具方法
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString()
}

// 修改状态文本方法
const getStatusText = (status) => {
  const statusMap = {
    0: '未提交',
    1: '已提交未批改',
    2: '已批改'
  }
  return statusMap[status]
}

// 修改状态样式方法

// 生命周期钩子
onMounted(() => {
  fetchWorkInfo()
  fetchStudentWorks()
})
</script>

<style scoped>
.work-manage {
  padding: 20px;
}

.work-info {
  margin-bottom: 20px;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.filter-section {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.operations {
  display: flex;
  gap: 10px;
}

.tags {
  margin: 10px 0;
  display: flex;
  gap: 10px;
}

.content {
  margin-top: 10px;
  color: #666;
}

.top_r {
  display: block;
  flex-direction: row;
  font-family: PingFangSC, PingFangSC-Medium;
  font-weight: 500;
  text-align: left;
  color: #4285f4;
  line-height: 8px;
}

.work-preview-info {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.work-preview-content {
  min-height: 200px;
}

.preview-file {
  margin: 10px 0;
}

.preview-image {
  max-width: 100%;
  max-height: 500px;
  object-fit: contain;
}

.file-info {
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.no-content {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}
</style>
